/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  AsyncStorage,
  Image,
  TouchableOpacity,
  TouchableHighlight,
  Platform,
  Dimensions,
  Modal,
  TextInput,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';
import ImagePicker from 'react-native-image-picker';
import * as Progress from 'react-native-progress';
import sha1 from 'sha1'
import Request from '../Common/Request';
import Config from '../Common/Config';

const {width, height} = Dimensions.get('window')
let options = {
  title: '选择头像',
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照',
  chooseFromLibraryButtonTitle: '从相册...',
  customButtons: [
    {name: '自定义', title: '飞鱼湾'},
  ],
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

CLOUDINARY = {
  cloud_name: 'baobao',
  api_key: '419894924147545',
  api_secret: '38Uui7Si3EhehAZZKRI9uh5lSDg',
  base: 'https://res.cloudinary.com/baobao',
  image: 'https://api.cloudinary.com/v1_1/baobao/image/upload',
  video: 'https://api.cloudinary.com/v1_1/baobao/video/upload',
  audio: 'https://api.cloudinary.com/v1_1/baobao/raw/upload',
}


export default class Account extends Component {
    constructor(props) {
        super(props)

        this.state = {
            isLogined: false,
            account: null,
            modalAnimationType: 'slide',//none slide fade
            modalVisible: false,//模态场景是否可见
            modaltransparent: true,//是否透明显示
        }

        this._addUserAvatar = this._addUserAvatar.bind(this)
        this._selectAvatar = this._selectAvatar.bind(this)
        this._uploadToCloudinary = this._uploadToCloudinary.bind(this)
        this._asyncUpdateUser = this._asyncUpdateUser.bind(this)
        this._editUserInfo = this._editUserInfo.bind(this)
        this._commentViewVisible = this._commentViewVisible.bind(this)
        this._startShow = this._startShow.bind(this)
        this._itemChanged = this._itemChanged.bind(this)
    }

    componentDidMount() {
        this._asyncGetAccountInfo()
    }

    _addUserAvatar() {
        alert('add')
    }

    _commentViewVisible(visible) {
        console.log(visible);
        if (this.state.modalVisible !== visible) {
            this.setState({
                modalVisible: visible
            })
        }
    }

    _startShow() {
        console.log('show modal')
    }

    _editUserInfo() {
        this._commentViewVisible(true)
    }

    _itemChanged(key, value) {
        let account = this.state.account
        account[key] = value

        this.setState({
            account: account
        })
    }

    _selectAvatar() {
        ImagePicker.showImagePicker(options, (response) => {
          console.log('Response = ', response);

          if (response.didCancel) {
            console.log('User cancelled image picker');
          }
          else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
          }
          else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton);
          }
          else {
              let source
            // 第一种方法: data - base64
            // const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
            source = 'data:image/jpeg;base64,' + response.data

            // 在自己服务器中生成签名
            let timestamp = Date.now()
            let tags = 'app,avatar'
            let folder = 'avatar'
            let signatureUrl = Config.api.base + Config.api.signature
            let accessToken = this.state.account.accessToken
            Request.post(signatureUrl, {
                accessToken: accessToken,
                tags: tags,
                folder: folder,
                timestamp: timestamp,
            })
            .then((data) => {
                if (data && data.success) {
                    // 打印服务器生成的签名
                    console.log('服务器生成的签名' + data.data);

                    // 自己在本地生成签名
                    let signature = 'folder=' + folder + '&tags=' + tags + '&timestamp=' + timestamp + CLOUDINARY.api_secret

                    signature = sha1(signature)

                    // 开始上传图床
                    let body = new FormData()
                    body.append('folder', folder)
                    body.append('tags', tags)
                    body.append('api_key', CLOUDINARY.api_key)
                    body.append('signature', signature)
                    body.append('resource_type', 'image')
                    body.append('file', source)
                    body.append('timestamp', timestamp)


                    this._uploadToCloudinary(body)
                }
            })
            .catch((error) => {
                console.log(error);
            })

            // or a reference to the platform specific asset location
            // 第二种方法: 图片地址

            // if (Platform.OS === 'ios') {
            //   source = response.uri.replace('file://', '');
            // } else {
            //   source = response.uri;
            // }
            // let newAccount = this.state.account
            // newAccount.avatar = source
            // this.setState({
            //   account: newAccount
            // });
          }
        });
    }

    _uploadToCloudinary(body) {
        let uploadRequest = new XMLHttpRequest()
        let url = CLOUDINARY.image
        uploadRequest.open('POST', url)
        uploadRequest.send(body)

        if (!this.state.isUploadingAvatar) {
            this.setState({
                isUploadingAvatar: true,
                progress: 0,
            })
        }

        uploadRequest.onload = () => {
            if (uploadRequest.status !== 200) {
                return alert('请求失败' + uploadRequest.responseText)
            }
            if (!uploadRequest.responseText) {
                return alert('图床返回一个空消息体')
            }
            let response
            try {
                let responseText = uploadRequest.responseText
                console.log(responseText);
                response = JSON.parse(responseText)
            } catch (e) {
                console.log(e);
            }

            if (response && response.public_id) {
                console.log('上传成功');
                // https://res.cloudinary.com/baobao/image/upload/v1479657279/avatar/ztarllivquayzrp1jhww.jpg
                let url = CLOUDINARY.base + '/' + response.resource_type + '/' + response.type + '/v' + response.version + '/' + response.public_id + '.' + response.format
                console.log('生成到图床的图片url: ' + url);
                console.log('上传到图床后图片url: ' + response.secure_url);
                let newAccount = this.state.account
                newAccount.avatar = url
                this.setState({
                    account: newAccount,
                    isUploadingAvatar: false,
                })

                // 把用户信息上传服务器
                this._asyncUpdateUser()
            }
        }

        if (uploadRequest.upload) {
            uploadRequest.upload.onprogress = (event) => {
                if (event.lengthComputable) {
                    let percent = Number((event.loaded / event.total).toFixed(2))
                    this.setState({
                        progress: percent,
                    })
                }
            }
        }
    }

    _asyncUpdateUser() {
        // 本地存储
        AsyncStorage.setItem('Account', JSON.stringify(this.state.account))
        .then(() => {
            console.log('更新本地成功');
        })
        .catch((err) => {
            console.log(err);
        })


        Request.post(Config.api.base + Config.api.saveUserInfo, {
            accessToken: 'kelvin',
            avatar: this.state.avatar,
        })
        .then((responseData) => {
            if (responseData && responseData.success) {
                alert('保存用户信息成功')
            }
        })
        .catch((err) => {
            console.log(err);
        })
    }

    _asyncGetAccountInfo() {
        AsyncStorage.getItem('Account')
        .then((data) => {
            if (data) {
                let account = JSON.parse(data)
                if (account && account.accessToken) {
                    this.setState({
                        isLogined: true,
                        account: account,
                    })
                }
            }
        })
        .catch((error) => {
            console.log(error);
        })
    }

    render() {
        let account = this.state.account
        console.log('Login' + JSON.stringify(account));
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.headerText}>
                        用户资料
                    </Text>
                    <Text style={styles.edit} onPress={this._editUserInfo}>
                        编辑
                    </Text>
                </View>
                {this.state.isLogined ?
                    <TouchableOpacity onPress={this._selectAvatar}>
                        <Image style={styles.avatarContainer} source={{uri: account.avatar}}>
                            <View style={styles.avatarBox1}>
                                {this.state.isUploadingAvatar ?
                                    <Progress.Circle
                                        size={70}
                                        progress={this.state.progress}
                                        showsText={true}
                                        color={'#ee735c'}
                                    />
                                    :
                                    <Image
                                        style={styles.avatarImg}
                                        source={{uri: 'http://img06.tooopen.com/images/20160808/tooopen_sl_174524078475.jpg'}}
                                    />
                                }

                            </View>
                            <Text style={styles.avatarText}>
                                点击更换头像
                            </Text>
                        </Image>
                    </TouchableOpacity>

                    :
                    <View style={styles.avatarContainer}>
                        <Text style={styles.avatarText}>
                            添加用户头像
                        </Text>
                        <TouchableHighlight onPress={this._addUserAvatar}>
                            <View style={styles.avatarBox}>
                                {this.state.isUploadingAvatar ?
                                    <Progress.Circle
                                        size={70}
                                        progress={this.state.progress}
                                        showsText={true}
                                        color={'#ee735c'}
                                    />
                                    :
                                    <Icon
                                        name='md-add'
                                        size={45}
                                        style={styles.plusIcon}
                                    />
                                }

                            </View>
                        </TouchableHighlight>
                    </View>
                }

                <Modal
                  animationType={this.state.animationType}
                  transparent={this.state.transparent}
                  visible={this.state.modalVisible}
                  onRequestClose={() => { this._commentViewVisible(false) } }
                  onShow={this._startShow}
                >
                    <View style={styles.modalContainer}>
                        <Icon
                            name='ios-close-outline'
                            size={40}
                            style={styles.closeIcon}
                            onPress={ () => this._commentViewVisible(false)}
                        />
                        <View style={styles.itemBox}>
                            <Text style={styles.itemName}>
                                昵称
                            </Text>
                            <TextInput
                                placeholder="昵称"
                                placeholderTextColor='#ccc'
                                autoCorrect={false}
                                autoCapitalize="none"
                                underlineColorAndroid="transparent"
                                defaultValue={account && account.nickname}
                                onChangeText={(text) => {
                                    this._itemChanged('nickname', text)
                                }}
                                style={styles.itemInput}
                            />
                        </View>
                        <View style={styles.itemBox}>
                            <Text style={styles.itemName}>
                                年龄
                            </Text>
                            <TextInput
                                placeholder="年龄"
                                placeholderTextColor='#ccc'
                                autoCorrect={false}
                                autoCapitalize="none"
                                underlineColorAndroid="transparent"
                                defaultValue={account && account.age}
                                onChangeText={(text) => {
                                    this._itemChanged('age', text)
                                }}
                                style={styles.itemInput}
                            />
                        </View>
                        <View style={styles.itemBox}>
                            <Text style={styles.itemName}>
                                性别
                            </Text>
                            <Icon
                                name='ios-paw'
                                size={30}
                                style={[styles.gender,
                                        (account && (account.gender === 'male')) && styles.genderChecked]}
                                onPress={ () => this._itemChanged('gender', 'male')}
                            >
                                男宝宝
                            </Icon>
                            <Icon
                                name='ios-paw'
                                size={30}
                                style={[styles.gender,
                                        (account && (account.gender === 'female')) && styles.genderChecked]}
                                onPress={ () => this._itemChanged('gender', 'female')}
                            >
                                女宝宝
                            </Icon>

                        </View>
                    </View>
                </Modal>

                <View style={styles.verifyBtnBox}>
                    <Text style={styles.registerBtn} onPress={this.props.logout}>
                        退出登录
                    </Text>
                </View>

            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#F5FCFF',
    },
    header: {
        marginTop: Platform.OS === 'ios' ? 20 : 0,
        paddingTop: 25,
        paddingBottom: 12,
        backgroundColor: '#ee735c',
        flexDirection: 'row',
        justifyContent: 'center',
    },
    headerText: {
        fontSize: 16,
        fontWeight: '600',
        textAlign: 'center',
        color: '#fff',
    },
    edit: {
        position: 'absolute',
        right: 10,
        fontSize: 15,
        fontWeight: '600',
        textAlign: 'center',
        color: 'white',
    },
    avatarContainer: {
        width: width,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#666',
    },
    avatarText: {
        marginTop: 20,
        marginBottom: 20,
        fontSize: 18,
        textAlign: 'center',
        color: 'white',
    },
    avatarBox: {
        marginTop: 20,
        marginBottom: 20,
        backgroundColor: 'white',
    },
    plusIcon: {
        padding: 20,
        fontSize: 26,
        color: '#666',
    },
    avatarBox1: {
        marginTop: 20,
        backgroundColor: 'transparent',
        justifyContent: 'center',
        alignItems: 'center',
    },
    avatarImg: {
        width: 60,
        height: 60,
        borderRadius: 30,
        borderWidth: 1,
        borderColor: 'red',
    },
    modalContainer: {
        marginTop: 20,
        width: width,
    },
    closeIcon: {
        marginTop: 20,
        marginLeft: 20,
        width: 40,
        height: 40,
    },
    itemBox: {
        marginTop: 10,
        marginLeft: 20,
        marginRight: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#ddd',
        height: 50,
    },
    itemName: {
        fontSize: 16,
        color: '#666',
        marginRight: 10,
        fontWeight: '600',
        textAlign: 'center',
    },
    itemInput: {
        flex: 1,
        fontSize: 18,
        height: 50,
    },
    gender: {
        backgroundColor: '#ccc'
    },
    genderChecked: {
        backgroundColor: 'red'
    },

    verifyBtnBox: {
        marginTop: 10,
        marginLeft: 10,
        width: width - 20,
        height: 50,
        borderWidth: 1,
        borderColor: 'gray',
        borderRadius: 4,
        backgroundColor: '#ccc',
        justifyContent: 'center',
    },
    registerBtn: {
        fontSize: 18,
        textAlign: 'center',
        color: 'red',
    },
});
